package admin

import (
	"editor/constant"
	"editor/service/mdFile"
	"editor/store"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
)

func AddDirHandler(c *gin.Context) {
	dirName := c.PostForm("dirName")
	if dirName == "" {
		c.JSON(http.StatusOK, constant.Response{Msg: "目录名为空", Code: 1})
		return
	}

	sortNum := cast.ToInt64(c.PostForm("sortNum"))

	isRepeat, err := mdFile.CheckCategoryIsRepeat(c, dirName, 0)
	if err != nil {
		store.Errorf(c, err, "dirName:%s,sortNum:%d", dirName, sortNum)
		c.JSON(http.StatusOK, constant.Response{Msg: "CheckTitleIsRepeat failed", Code: 3})
		return
	}
	if isRepeat {
		c.JSON(http.StatusOK, constant.Response{Msg: "dirName is repeat", Code: 4})
		return
	}

	id, err := mdFile.AddDir(c, dirName, sortNum)
	if err != nil {
		store.Errorf(c, err, "AddDir failed dirName:%s,sortNum:%d", dirName, sortNum)
		c.JSON(http.StatusOK, constant.Response{Msg: "add mdFile failed", Code: 5})
		return
	}

	c.JSON(http.StatusOK, constant.Response{Msg: "Success", Code: 0, Data: map[string]interface{}{"id": id}})
	return
}
